<script lang="ts" setup>
import { ref, shallowRef, watch, nextTick, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import pieChart from './options/pie-chart'
import barChart from './options/bar-chart'
import ccpieChart from './options/ccpie-chart'
import lineChart from './options/line-chart'
import homeBarChart from './options/homeBar-chart'
// char图组件

type Props = {
  // echarts类型
  chartType: string
  // 数据
  chartData: any
  // 配置
  chartOptions?: any
}

const emit = defineEmits(['click-chart'])

const props = withDefaults(defineProps<Props>(), {
  chartType: () => '',
  chartData: () => [],
  chartOptions: () => ({}),
})

/* 生命周期 */
onMounted(() => {
  window.addEventListener('resize', resizeChart)
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
})

/* 监听传递的数据变化 */
watch(
  () => props.chartData,
  () => {
    nextTick(() => {
      initChart()
    })
  },
  { deep: true },
)

// charts
const echarRef = ref()
const char = shallowRef()

/* charts图初始化 */
const initChart = () => {
  if (char.value) {
    char.value.dispose()
  }
  const { chartType, chartData } = props
  if (!chartData) return
  let options = {}
  switch (chartType) {
    case 'pie':
      options = pieChart(chartData)
      break
    case 'bar':
      options = barChart(chartData)
      break
    case 'ccpie':
      options = ccpieChart(chartData)
      break
    case 'line':
      options = lineChart(chartData)
      break
    case 'homeBar':
      options = homeBarChart(chartData)
      break
  }
  char.value = echarts.init(echarRef.value)
  char.value.setOption(options)

  // charts图点击事件
  char.value.on('click', (params: any) => {
    emit('click-chart', params)
  })
}

/* 监听浏览器 */
const resizeChart = () => {
  if (char.value) {
    char.value.resize()
  }
  // 组件charts图
}
</script>
<template>
  <div class="echarts" ref="echarRef"></div>
</template>
<style lang="scss" scoped>
.echarts {
  width: 100%;
  height: 100%;
}
</style>
